<template>
  <div class="info_panel">
    <div :style="{display: show ? 'block' : 'none'}">
      <img :src="order.avatar" alt="头像" width="20px" height="20px" class="img_avatar">
      <span>{{order.nickname}} 刚刚购买了{{order.total}}单</span>
    </div>
  </div>
</template>
<script>
import { ORDER_BROADCAST } from "@/api/order";

export default {
  name: "order-broadcast",

  data() {
    return {
      orders: [],
      index: 0,
      timer: 0,
      show: false,
      lastGetTime: 0
    };
  },

  computed: {
    order() {
      if (this.index >= this.orders.length) {
        return {
          nickname: "",
          avatar: "",
          total: ""
        };
      }

      return this.orders[this.index];
    }
  },

  activated() {
    if ((Date.now() - this.lastGetTime) < 60000) {
      this.beginShow();
      return;
    }

    const user = this.getUser();

    this.$reqGet(
      ORDER_BROADCAST,
      {
        centerId: user.centreId,
        limit: 10
      },
      {
        hideLoading: true
      }
    ).then(res => {
      this.orders = res.data.data;
      this.lastGetTime = Date.now();
      this.beginShow();
    });
  },

  deactivated() {
    this.endShow();
  },

  methods: {
    beginShow() {
      let vm = this;
      this.timer = setInterval(() => {
        vm.showBroadcast();
      }, 2000);
    },
    endShow() {
      clearInterval(this.timer);
    },
    showBroadcast() {
      const now = new Date();

      //截团不显示
      if (now.getHours() == 20 && now.getMinutes() < 30) {
        return;
      }

      if (this.orders.length === 0) {
        return;
      }

      if (this.index >= this.orders.length) {
        this.index = 0;
      }

      this.show = true;
      let vm = this;
      setTimeout(() => {
        vm.show = false;
        ++vm.index;
      }, 1000);
    }
  }
};
</script>
<style lang="scss" scoped>
.info_panel {
  position: fixed;
  z-index: 100;
  top: 50px;
  left: 15px;
  background-color: $red;
  color: white;
  border-radius: 20px;
  opacity: 0.7;
  padding: 0 10px 0 10px;
  font-size: 10px;
}
.img_avatar {
  border-radius: 50%;
  vertical-align: middle;
  margin: 2px 0 2px 0;
}
</style>
